<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 老版本,支付1.0.暂时未使用了.
 * 头条支付相关接口,接收小程序的支付调用
 * Class Controller_Pc_Api_V2_Payment_Wechatapp
 */
class Controller_Pc_Api_V2_Payment_Toutiao extends Controller_Pc_Api_v2_Base
{
    private $result;

    private $app_id;
    private $salt;

    public function before()
    {
        parent::before();
        // 检查会员信息
        $token       = Common::remove_xss($this->request_data->token);
        $check_token = Model_Api_V2_Pub::token_decode($token);
        if ($check_token['status']) {
            $this->mid = $check_token['mid'];
        }
        $toutiao_config_params = array(
            'cfg_toutiao_appid',
            'cfg_toutiao_danbao_salt',
            'cfg_toutiao_danbao_token',
        );
        $config                = Model_Sysconfig::get_configs(0, $toutiao_config_params, 0);
        $this->app_id          = $config['cfg_toutiao_appid'];
        $this->salt            = $config['cfg_toutiao_danbao_salt'];
        $this->result          = array(
            'status' => false,//默认状态为成功
            'msg' => '操作失败.',//默认的提示消息
            'data' => array()
        );
    }

    /**
     * 计算签名
     */
    protected function getSign($params, $salt)
    {
        unset($params["sign"]);
        unset($params["app_id"]);
        unset($params["thirdparty_id"]);
        $paramArray = [];
        foreach ($params as $param) {
            $paramArray[] = trim($param);
        }
        $paramArray[] = trim($salt);
        sort($paramArray, 2);
        $signStr = trim(implode('&', $paramArray));
        return md5($signStr);
    }

    public static function httpPost($url, $postfields = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$postfields) {
            return 'data is null';
        }
        if (is_array($postfields)) {
            $postfields = json_encode($postfields, 320);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($postfields),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     * 退款
     */
    public function action_create_refund()
    {

        if ($this->mid) {
            // 验证订单状态
            //$ordersn = Product::get_ordersn(199);
            $ordersn = Common::remove_xss($this->request_data->ordersn);
            $reason  = Common::remove_xss($this->request_data->reason);

            $orderInfo = Model_Member_Order::order_info($ordersn);

            if ($orderInfo && $orderInfo['status'] == 2 && $orderInfo['memberid'] == $this->mid) {
                //支付金额
                $totalprice = $orderInfo['payprice'];
                // 获取会员小程序openid
                $member_third = DB::select()->from("member_third")
                    ->where("mid", "=", $this->mid)
                    ->and_where("come_from", "=", "toutiao")
                    ->execute()
                    ->current();

                if ($member_third && $member_third['tt_openid']) {
                    //获取头条商户号

                    $total_amount = $totalprice * 100;  //抖音是 “ 分 ”作为单位
                    //$ip = St_Functions::get_ip();

                    $domain     = St_Functions::get_main_host();
                    $m_main_url = $GLOBALS['cfg_m_main_url'];
                    if (empty($m_main_url) || $m_main_url == $domain) {
                        $mobile_domain = $domain . '/phone/toutiao/mobile/index/refund_notify';
                    } else {
                        $mobile_domain = $m_main_url . '/toutiao/mobile/index/refund_notify';
                    }

                    //业务数据
                    $params = array(
                        'app_id' => $this->app_id,
                        'out_order_no' => 'sn' . $ordersn . rand(111, 999),    //商户唯一订单号
                        'refund_amount' => $total_amount,
                        'out_refund_no' => $ordersn . time(),
                        'reason' => $reason ? $reason : '协商退款',
                        'notify_url' => $mobile_domain,
                    );
                    //公共请求参数
                    $params['sign'] = $this->getSign($params, $this->salt);
                    //请求服务端支付接口（这里用的是 GuzzleHttp 对象）
                    $res = json_decode(self::httpPost('https://developer.toutiao.com/api/apps/ecpay/v1/create_refund', $params), true);
                    if ($res['err_no'] == '0') {
                        $this->result['status'] = true;
                        $this->result['data']   = $res['data'];
                        $this->result['msg']    = '发起退款成功';
                    } else {
                        $this->result['status'] = false;
                        $this->result['data']   = $res;
                        $this->result['msg']    = '发起退款失败';
                    }
                } else {
                    $this->result['msg'] = '会员信息有误';
                }
            } else {
                $this->result['msg'] = '订单信息有误';
            }
        } else {
            $this->result['msg'] = '订单信息有误';
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 获取 头条预支付单号
     */
    public function action_create_order()
    {

        if ($this->mid) {
            // 验证订单状态
            $ordersn = Common::remove_xss($this->request_data->ordersn);
            // 验证订单
            $checkOrder = Model_Api_V2_Payment::ordersn_checked($ordersn);
            if (!$checkOrder['status']) {
                $this->send_datagrams($this->client_info['id'], $checkOrder, $this->client_info['secret_key']);
            }

            $orderInfo = Model_Member_Order::order_info($ordersn);

            //"0元"订单,免费产品
            if ($orderInfo['pay_price'] == 0) {
                $zero_res = Model_Api_V2_Payment::zero_pay($ordersn);
                if ($zero_res['status']) {
                    $sign                     = $zero_res['data']['sign'];
                    $zero_res['data']         = $orderInfo;
                    $zero_res['data']['sign'] = $sign;
                }
                $zero_res['status'] = false;
                $this->send_datagrams($this->client_info['id'], $zero_res, $this->client_info['secret_key']);
            }

            if ($orderInfo && $orderInfo['status'] == 1 && $orderInfo['memberid'] == $this->mid) {
                //支付金额
                $totalprice = $orderInfo['payprice'];
                // 获取会员小程序openid
                $member_third = DB::select()->from("member_third")
                    ->where("mid", "=", $this->mid)
                    ->and_where("come_from", "=", "toutiao")
                    ->execute()
                    ->current();

                if ($member_third && $member_third['tt_openid']) {
                    $total_amount = $totalprice * 100;  //抖音是 “ 分 ”作为单位
                    //$ip = St_Functions::get_ip();

                    $domain     = St_Functions::get_main_host();
                    $m_main_url = $GLOBALS['cfg_m_main_url'];
                    if (empty($m_main_url) || $m_main_url == $domain) {
                        $mobile_domain = $domain . '/phone/toutiao/mobile/index/pay_notify';
                    } else {
                        $mobile_domain = $m_main_url . '/toutiao/mobile/index/pay_notify';
                    }

                    //业务数据
                    $params         = array(
                        'app_id' => $this->app_id,
                        'out_order_no' => 'sn' . $ordersn . rand(111, 999),    //商户唯一订单号
                        'total_amount' => $total_amount,
                        'subject' => $ordersn . '产品购买',
                        'body' => $ordersn . '产品购买',
                        'valid_time' => 900,
                        'notify_url' => $mobile_domain,
                    );
                    $params['sign'] = $this->getSign($params, $this->salt);
                    //请求服务端支付接口（这里用的是 GuzzleHttp 对象）
                    $res = json_decode(self::httpPost('https://developer.toutiao.com/api/apps/ecpay/v1/create_order', $params), true);
                    if ($res['err_no'] == '0') {
                        $this->result['status'] = true;
                        $this->result['data']   = $res['data'];
                        $this->result['msg']    = '创建成功';
                    } else {
                        $this->result['status'] = false;
                        $this->result['data']   = $res;
                        $this->result['msg']    = '创建失败';
                    }
                } else {
                    $this->result['msg'] = '会员信息有误';
                }
            } else {
                $this->result['msg'] = '订单信息有误';
            }
        } else {
            $this->result['msg'] = '订单信息有误';
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 支付数据
     */
    public function action_get_pay_data()
    {
        if ($this->mid) {

            // 验证订单状态
            $ordersn = Common::remove_xss($this->request_data->ordersn);

            // 验证订单
            $checkOrder = Model_Api_V2_Payment::ordersn_checked($ordersn);

            if (!$checkOrder['status']) {
                $this->send_datagrams($this->client_info['id'], $checkOrder, $this->client_info['secret_key']);
            }

            $orderInfo = Model_Member_Order::order_info($ordersn);

            //"0元"订单,免费产品
            if ($orderInfo['pay_price'] == 0) {
                $zero_res = Model_Api_V2_Payment::zero_pay($ordersn);
                if ($zero_res['status']) {
                    $sign                     = $zero_res['data']['sign'];
                    $zero_res['data']         = $orderInfo;
                    $zero_res['data']['sign'] = $sign;
                }
                $zero_res['status'] = false;
                $this->send_datagrams($this->client_info['id'], $zero_res, $this->client_info['secret_key']);
            }

            if ($orderInfo && $orderInfo['status'] == 1 && $orderInfo['memberid'] == $this->mid) {
                //支付金额
                $totalprice = $orderInfo['payprice'];
                // 获取会员小程序openid
                $member_third = DB::select()->from("member_third")
                    ->where("mid", "=", $this->mid)
                    ->and_where("come_from", "=", "toutiao")
                    ->execute()
                    ->current();


                if ($member_third && $member_third['tt_openid']) {
                    $openid                 = $member_third['tt_openid'];
                    $params                 = array(
                        'ordersn' => $ordersn,
                        'totalprice' => $totalprice,
                        'openid' => $openid,
                    );
                    $this->result['data']   = $params;
                    $pay_data               = Model_Api_V2_Payment_Toutiao::pay($params);
                    $this->result['status'] = true;
                    $this->result['data']   = $pay_data;
                    $this->result['msg']    = '获取成功';

                } else {
                    $this->result['msg'] = '会员信息有误';
                }
            } else {
                $this->result['msg'] = '订单信息有误';
            }
        } else {
            $this->result['msg'] = '订单信息有误';
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 查询订单
     */
    public function action_query_order_status()
    {
        $api_order_sn = Common::remove_xss($this->request_data->ordersn);
        $orderInfo    = DB::select('status')->from('member_order')
            ->where('api_channel_orderno', '=', $api_order_sn)
            ->execute()
            ->current();
        if ($orderInfo) {
            $this->result['status'] = true;
            $this->result['msg']    = '操作成功';
            $this->result['data']   = $orderInfo['status'];
        } else {
            $this->result['status'] = false;
            $this->result['msg']    = '未查询到订单';
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }
}